package ift605.tp3.a;

import jade.core.Agent;
import jade.core.behaviours.CyclicBehaviour;
import jade.domain.DFService;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.lang.acl.ACLMessage;

public class ManWhoListenAgent extends Agent
{
    private static final long serialVersionUID = 1L;
    
    @Override
    protected void setup()
    {
        System.out.println(getLocalName() + " sits down, ready to listen ...");
        try
        {
            final DFAgentDescription dfd = new DFAgentDescription();
            dfd.setName(getAID());
            DFService.register(this, dfd);
            
            addBehaviour(new CyclicBehaviour(this)
            {
                private static final long serialVersionUID = 1L;
                
                @Override
                public void action()
                {
                    final ACLMessage msg = receive();
                    
                    if (msg != null)
                    {
                        System.out.println(getLocalName() + " listen to " + msg.getSender().getLocalName() + " and she says: " + msg.getContent());
                        
                        final ACLMessage confirm = new ACLMessage(ACLMessage.CONFIRM);
                        confirm.setContent("I understand");
                        confirm.addReceiver(msg.getSender());
                        send(confirm);
                        doDelete();
                    }
                    else
                    {
                        // if no message is arrived, block the behaviour
                        block();
                    }
                }
            });
        }
        catch (final Exception e)
        {
            System.out.println("This is too much for this poor man: " + e);
            e.printStackTrace();
        }
    }
}
